#!/bin/bash
# ========================================
# 部署测试脚本
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 打印标题
print_title() {
    echo ""
    print_message "$BLUE" "========================================="
    print_message "$BLUE" "  $1"
    print_message "$BLUE" "========================================="
    echo ""
}

# 打印测试结果
print_result() {
    local result=$1
    local name=$2
    local detail=$3
    
    if [ "$result" = "pass" ]; then
        echo "  ✅ $name - 通过"
        [ -n "$detail" ] && echo "     $detail"
    elif [ "$result" = "fail" ]; then
        echo "  ❌ $name - 失败"
        [ -n "$detail" ] && echo "     $detail"
    else
        echo "  ⚠️  $name - 警告"
        [ -n "$detail" ] && echo "     $detail"
    fi
}

# 初始化计数器
PASS_COUNT=0
FAIL_COUNT=0
WARN_COUNT=0
TOTAL_COUNT=0

# 测试函数
run_test() {
    local name=$1
    local command=$2
    local expected_result=${3:-0}
    
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    
    if eval "$command" > /dev/null 2>&1; then
        if [ "$expected_result" = "0" ]; then
            print_result "pass" "$name"
            PASS_COUNT=$((PASS_COUNT + 1))
            return 0
        else
            print_result "fail" "$name"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            return 1
        fi
    else
        if [ "$expected_result" = "1" ]; then
            print_result "pass" "$name"
            PASS_COUNT=$((PASS_COUNT + 1))
            return 0
        else
            print_result "fail" "$name"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            return 1
        fi
    fi
}

# 显示横幅
print_banner() {
    clear
    print_message "$GREEN" "╔════════════════════════════════════════╗"
    print_message "$GREEN" "║                                        ║"
    print_message "$GREEN" "║     若依系统部署测试脚本 v1.0         ║"
    print_message "$GREEN" "║                                        ║"
    print_message "$GREEN" "╚════════════════════════════════════════╝"
    echo ""
}

# 测试系统环境
test_environment() {
    print_title "🔍 测试系统环境"
    
    run_test "Java 已安装" "command -v java"
    if command -v java &> /dev/null; then
        JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
        print_result "pass" "Java 版本" "$JAVA_VERSION"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
    
    run_test "Maven 已安装" "command -v mvn"
    if command -v mvn &> /dev/null; then
        MVN_VERSION=$(mvn -version | head -n 1 | awk '{print $3}')
        print_result "pass" "Maven 版本" "$MVN_VERSION"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
    
    run_test "Node.js 已安装" "command -v node"
    if command -v node &> /dev/null; then
        NODE_VERSION=$(node -v)
        print_result "pass" "Node.js 版本" "$NODE_VERSION"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
    
    run_test "npm 已安装" "command -v npm"
    if command -v npm &> /dev/null; then
        NPM_VERSION=$(npm -v)
        print_result "pass" "npm 版本" "$NPM_VERSION"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
    
    run_test "MySQL客户端 已安装" "command -v mysql"
}

# 测试数据库
test_database() {
    print_title "📊 测试数据库"
    
    # 测试数据库连接
    if mysql -h localhost -u root -p123 -e "SELECT 1;" > /dev/null 2>&1; then
        print_result "pass" "数据库连接" "localhost:3306"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
        
        # 测试数据库是否存在
        DB_EXISTS=$(mysql -h localhost -u root -p123 \
            -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='ry-vue';" 2>/dev/null \
            | grep -c "ry-vue" || true)
        
        if [ "$DB_EXISTS" -eq 1 ]; then
            print_result "pass" "数据库 ry-vue 已创建"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 统计表数量
            TABLE_COUNT=$(mysql -h localhost -u root -p123 ry-vue \
                -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='ry-vue';" 2>/dev/null \
                | tail -n 1)
            print_result "pass" "数据库表数量" "$TABLE_COUNT 张表"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 检查学习模块表
            USER_TABLES=$(mysql -h localhost -u root -p123 ry-vue \
                -e "SHOW TABLES LIKE 'user_%';" 2>/dev/null | tail -n +2 | wc -l)
            if [ "$USER_TABLES" -gt 0 ]; then
                print_result "pass" "学习模块表" "$USER_TABLES 张表"
                PASS_COUNT=$((PASS_COUNT + 1))
            else
                print_result "warn" "学习模块表" "未找到 user_* 表"
                WARN_COUNT=$((WARN_COUNT + 1))
            fi
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        else
            print_result "fail" "数据库 ry-vue" "不存在"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        fi
    else
        print_result "fail" "数据库连接失败" "请检查MySQL服务和密码"
        FAIL_COUNT=$((FAIL_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
}

# 测试后端服务
test_backend() {
    print_title "🚀 测试后端服务"
    
    # 检查进程
    BACKEND_PID=$(ps -ef | grep java | grep ruoyi-admin.jar | grep -v grep | awk '{print $2}')
    if [ -n "$BACKEND_PID" ]; then
        print_result "pass" "后端进程运行中" "PID: $BACKEND_PID"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
        
        # 检查端口监听
        if netstat -tuln | grep -q ":8080 "; then
            print_result "pass" "端口 8080 监听中"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 测试HTTP响应
            if curl -s http://localhost:8080 > /dev/null 2>&1; then
                print_result "pass" "HTTP 服务响应正常"
                PASS_COUNT=$((PASS_COUNT + 1))
                TOTAL_COUNT=$((TOTAL_COUNT + 1))
            else
                print_result "warn" "HTTP 服务" "无响应或启动中"
                WARN_COUNT=$((WARN_COUNT + 1))
                TOTAL_COUNT=$((TOTAL_COUNT + 1))
            fi
        else
            print_result "fail" "端口 8080 未监听"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        fi
        
        # 检查日志文件
        LOG_FILE="/root/workspace/3.1.0-dev/ruoyi/RuoYi-Vue/logs/ruoyi-admin.jar.log"
        if [ -f "$LOG_FILE" ]; then
            print_result "pass" "日志文件存在" "$LOG_FILE"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 检查是否有错误
            ERROR_COUNT=$(grep -c "ERROR" "$LOG_FILE" 2>/dev/null || echo "0")
            if [ "$ERROR_COUNT" -gt 0 ]; then
                print_result "warn" "日志中发现错误" "$ERROR_COUNT 条错误"
                WARN_COUNT=$((WARN_COUNT + 1))
            else
                print_result "pass" "日志无错误"
                PASS_COUNT=$((PASS_COUNT + 1))
            fi
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        else
            print_result "warn" "日志文件" "不存在"
            WARN_COUNT=$((WARN_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        fi
    else
        print_result "fail" "后端服务未运行"
        FAIL_COUNT=$((FAIL_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
}

# 测试前端服务
test_frontend() {
    print_title "🎨 测试前端服务"
    
    # 检查Nginx
    if systemctl is-active --quiet nginx 2>/dev/null; then
        print_result "pass" "Nginx 服务运行中"
        PASS_COUNT=$((PASS_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
        
        # 检查端口监听
        if netstat -tuln | grep -q ":80 "; then
            print_result "pass" "端口 80 监听中"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 测试HTTP响应
            if curl -s http://localhost > /dev/null 2>&1; then
                print_result "pass" "前端页面可访问"
                PASS_COUNT=$((PASS_COUNT + 1))
                TOTAL_COUNT=$((TOTAL_COUNT + 1))
            else
                print_result "fail" "前端页面无响应"
                FAIL_COUNT=$((FAIL_COUNT + 1))
                TOTAL_COUNT=$((TOTAL_COUNT + 1))
            fi
        else
            print_result "fail" "端口 80 未监听"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        fi
        
        # 检查部署目录
        DEPLOY_DIR="/usr/share/nginx/html/ruoyi"
        if [ -d "$DEPLOY_DIR" ]; then
            print_result "pass" "部署目录存在" "$DEPLOY_DIR"
            PASS_COUNT=$((PASS_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
            
            # 检查index.html
            if [ -f "$DEPLOY_DIR/index.html" ]; then
                print_result "pass" "index.html 存在"
                PASS_COUNT=$((PASS_COUNT + 1))
            else
                print_result "fail" "index.html 不存在"
                FAIL_COUNT=$((FAIL_COUNT + 1))
            fi
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        else
            print_result "fail" "部署目录不存在"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            TOTAL_COUNT=$((TOTAL_COUNT + 1))
        fi
        
        # 检查Nginx配置
        NGINX_CONF="/etc/nginx/conf.d/ruoyi.conf"
        if [ -f "$NGINX_CONF" ]; then
            print_result "pass" "Nginx配置文件存在"
            PASS_COUNT=$((PASS_COUNT + 1))
        else
            print_result "warn" "Nginx配置文件" "不存在"
            WARN_COUNT=$((WARN_COUNT + 1))
        fi
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    else
        print_result "fail" "Nginx 服务未运行"
        FAIL_COUNT=$((FAIL_COUNT + 1))
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
    fi
}

# 显示总结
show_summary() {
    print_title "📊 测试总结"
    
    TOTAL_TESTS=$((PASS_COUNT + FAIL_COUNT + WARN_COUNT))
    
    echo ""
    print_message "$BLUE" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print_message "$GREEN" "  ✅ 通过: $PASS_COUNT 项"
    print_message "$RED" "  ❌ 失败: $FAIL_COUNT 项"
    print_message "$YELLOW" "  ⚠️  警告: $WARN_COUNT 项"
    print_message "$BLUE" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    if [ $FAIL_COUNT -eq 0 ]; then
        print_message "$GREEN" "🎉 所有测试通过！系统部署成功！"
        echo ""
        print_message "$BLUE" "📌 访问地址:"
        print_message "$BLUE" "   • 前端: http://localhost"
        print_message "$BLUE" "   • 后端: http://localhost:8080"
        print_message "$BLUE" "   • 默认账号: admin / admin123"
    elif [ $FAIL_COUNT -le 2 ] && [ $PASS_COUNT -gt $FAIL_COUNT ]; then
        print_message "$YELLOW" "⚠️  部分测试失败，但主要功能可能正常"
        echo ""
        print_message "$BLUE" "💡 建议:"
        print_message "$BLUE" "   1. 查看上方失败的测试项"
        print_message "$BLUE" "   2. 检查相关服务和配置"
        print_message "$BLUE" "   3. 查看日志文件排查问题"
    else
        print_message "$RED" "❌ 多项测试失败，请检查部署"
        echo ""
        print_message "$BLUE" "💡 建议:"
        print_message "$BLUE" "   1. 运行 ./deploy_all.sh --check 检查环境"
        print_message "$BLUE" "   2. 重新执行部署脚本"
        print_message "$BLUE" "   3. 查看日志排查问题"
    fi
    
    echo ""
}

# 主函数
main() {
    print_banner
    
    print_message "$BLUE" "开始测试若依系统部署状态..."
    echo ""
    
    # 执行测试
    test_environment
    test_database
    test_backend
    test_frontend
    
    # 显示总结
    show_summary
}

# 运行主函数
main "$@"

